"""
@Author  : 康帅
@Time    : 2021/5/5 16:09
@Function: 合并字典的 6 种方法
"""
import itertools
from collections import ChainMap


def dict_1():
    """ 字典对象内置了一个 update 方法，用于把另一个字典更新到自己身上 """
    profile = {"name": "ks", "age": 27}
    ext_info = {"gender": "male"}
    profile.update(ext_info)
    print(profile)


def dict_2():
    """ 使用 ** 可以解包字典，解包完后再使用 dict 或者 {} 就可以合并 """
    profile = {"name": "ks", "age": 27}
    ext_info = {"gender": "male"}
    full_profile01 = {**profile, **ext_info}
    print(full_profile01)
    full_profile02 = dict(**profile, **ext_info)
    print(full_profile02)


def dict_3():
    """ 借助 itertools """
    profile = {"name": "ks", "age": 27}
    ext_info = {"gender": "male"}
    new_dict = dict(itertools.chain(profile.items(), ext_info.items()))
    print(new_dict)


def dict_4():
    """ 借助 ChainMap """
    profile = {"name": "ks", "age": 27}
    ext_info = {"gender": "male"}
    new_dict = dict(ChainMap(profile, ext_info))
    print(new_dict)


def dict_5():
    """ 使用dict.items() 合并 """
    profile = {"name": "ks", "age": 27}
    ext_info = {"gender": "male"}
    # full_profile = dict(profile.items() | ext_info.items())
    full_profile = dict(list(profile.items()) + list(ext_info.items()))
    print(full_profile)


def dict_6():
    """ 最酷炫的字典解析式 """
    profile = {"name": "ks", "age": 27}
    ext_info = {"gender": "male"}
    full_profile = {k: v for d in [profile, ext_info] for k, v in d.items()}
    print(full_profile)


if __name__ == '__main__':
    dict_1()
    dict_2()
    dict_3()
    dict_4()
    dict_5()
    dict_6()
